package com.ferry.id.pool.domain;

import javax.swing.text.Segment;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by daiyong
 */
public class PooledBuffer {
	private String namespace;
	private Pool[] pools;
	private volatile int currentPos;
	private volatile boolean nextReady;
	private volatile boolean initOk; //是否初始化完成
	private final AtomicBoolean threadRunning; //线程是否在运行中
	private final ReadWriteLock lock;

	private volatile int step;
	private volatile int minStep;
	private volatile long updateTimestamp;


	public PooledBuffer() {
		pools = new Pool[]{new Pool(this), new Pool(this)};
		currentPos = 0;
		nextReady = false;
		initOk = false;
		threadRunning = new AtomicBoolean(false);
		lock = new ReentrantReadWriteLock();
	}

	public String getNamespace() {
		return namespace;
	}

	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	public Pool[] getPools() {
		return pools;
	}

	public void setPools(Pool[] pools) {
		this.pools = pools;
	}

	public int getCurrentPos() {
		return currentPos;
	}

	public void setCurrentPos(int currentPos) {
		this.currentPos = currentPos;
	}

	public boolean isNextReady() {
		return nextReady;
	}

	public void setNextReady(boolean nextReady) {
		this.nextReady = nextReady;
	}

	public boolean isInitOk() {
		return initOk;
	}

	public void setInitOk(boolean initOk) {
		this.initOk = initOk;
	}

	public AtomicBoolean getThreadRunning() {
		return threadRunning;
	}

	public ReadWriteLock getLock() {
		return lock;
	}

	public int getStep() {
		return step;
	}

	public void setStep(int step) {
		this.step = step;
	}

	public int getMinStep() {
		return minStep;
	}

	public void setMinStep(int minStep) {
		this.minStep = minStep;
	}

	public long getUpdateTimestamp() {
		return updateTimestamp;
	}

	public void setUpdateTimestamp(long updateTimestamp) {
		this.updateTimestamp = updateTimestamp;
	}

	public Pool getCurrentPool() {
		return pools[currentPos];
	}

	public int nextPos() {
		return (currentPos + 1) % 2;
	}

	public void switchPos() {
		currentPos = nextPos();
	}

	public Lock rLock() {
		return lock.readLock();
	}

	public Lock wLock() {
		return lock.writeLock();
	}

}
